import { RouteView,BlankLayout } from "@/layouts/index";
import WebView from '@/modules/home/WebView.vue';
import constantRouterMap from "./constantRouterMap";
import config from '@/config/index';
import { checkAuth } from '@/appBase/service/auth';

/**
 * 生成异步路由
 * @param {Array} navMap 导航菜单配置 
 */
export function generateAsyncRouter(routerMap, routerPageMap) {
    // TODO: 当前暂时去除系统管理
    const item = routerMap.find(i=>i.path=='/system');
    const blacklist = ['/system/user','/system/menu','/system/dept','/system/post','/system/dict','/system/config','/system/notice','/system/log'];
    if(item&&item.children){
        // 系统管理,屏蔽无需开放的功能
        item.children=item.children.filter(i=>!blacklist.includes(i.path));
    }
    console.log('路由配置:',routerMap,'路由与页面配置:',routerPageMap);
    return generateRouteByRouterPageMap([{
        path: '/',
        children: routerMap,
        // redirect: config.homeIndex
    }, {
        path: '*', redirect: '/404'
    }], routerPageMap)
}

/**
 * 通过页面和路由间映射生成路由配置
 * @param {Array} routerMap 路由配置
 * @param {Array} routerPageMap 路由与页面配置
 */
export function generateRouteByRouterPageMap(routerMap, routerPageMap) {
    // return routerMap;
    for (let index = 0, len = routerMap.length; index < len; index++) {
        let navItem = routerMap[index];
        // 从映射表中读取页面详细信息,组装出路由
        for (let index1 = 0, len1 = routerPageMap.length; index1 < len1; index1++) {
            const ele = routerPageMap[index1];
            //  仅从可能存在于导航菜单的路由中读取配置
            if (navItem.path === ele.path) {
                let meta = {};
                if (!navItem.meta) navItem.meta = {};
                if (!ele.meta) ele.meta = {};
                meta = Object.assign(meta, ele.meta, navItem.meta);
                navItem = Object.assign({
                    props: (route) => Object.assign(route.query, route.params)
                }, ele, navItem);
                if (!navItem.name && navItem.path) navItem.name = navItem.path;
                navItem.meta = meta;
                break;
            }
        }
        if (navItem.children) {
            if (!navItem.component) navItem.component = RouteView|| BlankLayout;
            navItem.children = generateRouteByRouterPageMap(navItem.children, routerPageMap);
            // 一级目录默认设置图标
            if (navItem.meta&&!navItem.meta.icon) navItem.meta.icon = 'dashboard';
            const hasVisibleChildren = navItem.children.find(i=>i.hidden!=true);
            if (!hasVisibleChildren) {
                // 无任何一个子节点显示,则该目录无需展示
                navItem.hidden = true;
            }
        }else{
            if (!navItem.component&&!navItem.redirect){
                navItem.component = WebView;
                if (!navItem.name && navItem.path) navItem.name = navItem.path;
            }
        }
        
        routerMap[index] = navItem;
    }
    return routerMap;
}
